package com.dr.service.impl;

import com.dr.Enum.ExcepEnum;
import com.dr.common.pojo.FileFinalValue;
import com.dr.common.ution.DateUtil;
import com.dr.common.ution.ExportExcelUtil;
import com.dr.common.ution.StringUtil;
import com.dr.common.ution.ZipUtils;
import com.dr.db.StudentMapper;
import com.dr.exception.ServiceExcep;
import com.dr.pojo.Student;
import com.dr.pojo.SysConfig;
import com.dr.service.StudentInfoService;
import com.dr.service.SysConfigService;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by tugou on 2017/4/25.
 */
@Service
public class StudentInfoImpl implements StudentInfoService {

    @Autowired
    StudentMapper studentMapper;
    @Autowired
    SysConfigService sysConfigService;

    @Override
    public Student getStudent(String openId) {
        if (StringUtil.isNotEmpty(openId)){
            Student student = new Student();
            student.setOpenId(openId);
            List<Student> list = studentMapper.getStudent(student);
            if(list != null && list.size() != 0){
                return studentMapper.getStudent(student).get(0);
            }

        }
        return null;
    }

    @Override
    public List<Student> getStudentList(Student student) {
        if(student != null){
            if(student.getBespeak() != null && student.getBespeak() == 0)
                student.setBespeak(null);
            if(student.getLocationId() != null && student.getLocationId() == 0)
                student.setLocationId(null);
            if(StringUtil.isNotEmpty(student.getStartTime()))
                student.setStartTime(student.getStartTime().replace("-","")+"000000");
            if(StringUtil.isNotEmpty(student.getEndTime()))
                student.setEndTime(student.getEndTime().replace("-","")+"235959");
        }
        return studentMapper.getStudent(student);
    }

    @Override
    public void saveStudent(Student student) throws ServiceExcep{
        student.setCreateDate(DateUtil.now());
        student.setState(1);
        student.setBespeak(1);
        SysConfig config = new SysConfig();
        config.setConfigName("leanTime");
        List<SysConfig> configs = sysConfigService.getSysConfig(config);
        if(configs != null && configs.size() > 0)
            student.setOrderTime(configs.get(0).getConfigValue());
        else
            student.setOrderTime("4");
        int result = studentMapper.insertStudent(student);
        if (result == 0){
            throw new ServiceExcep(ExcepEnum.INSERTDATAEMPTY.getName(),ExcepEnum.INSERTDATAEMPTY.getIndex());
        }
    }

    @Override
    public void updateStudent(Student student) throws ServiceExcep {
        int result = studentMapper.updateStudent(student);
        if(result == 0){
            throw new ServiceExcep(ExcepEnum.INSERTDATAEMPTY.getName(),ExcepEnum.INSERTDATAEMPTY.getIndex());
        }
    }

    @Override
    public byte[] getStudentInfoFile(String id) throws Exception {
        String dirName = DateUtil.now()+Thread.currentThread().getId();
        String dir = FileFinalValue.PICTUREPATH+dirName;
        File dirFile = new File(dir);
        byte[] data = null;
        if(StringUtil.isNotEmpty(id)){
            Student student = new Student();
            student.setInPar(id);
            String [] arr = student.getInPar().split(",");
            List<Integer> ids = new ArrayList<>();
            for (int i = 0,len = arr.length;i<len;i++){
                ids.add(Integer.valueOf(arr[i]));
            }
            List<Student> list = studentMapper.getStudentById(ids);
            if(list == null && list.size() == 0){
                throw new ServiceExcep(ExcepEnum.QUERYRESULTISEMPTY.getName(),ExcepEnum.QUERYRESULTISEMPTY.getIndex());
            }
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet();
            ExportExcelUtil eeu = new ExportExcelUtil(workbook, sheet);
            String[] strArr = new String[] { "姓名", "性 别", "身份证号", "联系方式", "是否预约学车", "预约地点","报名时间","推荐人"};
            int colNum = strArr.length;
            int rowNO = 0;
            eeu.createColumnHeader(sheet, rowNO, 300, strArr);
            rowNO++;
            String[][]columnData = objToArray(list);
            sheet = eeu.createColumnData(sheet, rowNO,  columnData, list.size()+1);
            eeu.createSummaryRow(workbook, sheet, colNum, "合计：" + columnData.length, 180, "normal", "right");
            dirFile.mkdir();
            eeu.exportExcel(dir+"//学生数据.xls");
            /*for (int i = 0,len = list.size();i<len;i++){
                File fileA = new File(FileFinalValue.PICTUREPATH+FileFinalValue.SPLITSYMBOL+list.get(i).getCertificatesA());
                FileUtils.copyFileToDirectory(fileA,dirFile);
                new File(dir+"//"+list.get(i).getCertificatesA()).renameTo(new File(dir+FileFinalValue.SPLITSYMBOL+list.get(i).getCertificatesId()+"A.jpg"));
                File fileB = new File(FileFinalValue.PICTUREPATH+FileFinalValue.SPLITSYMBOL+list.get(i).getCertificatesB());
                FileUtils.copyFileToDirectory(fileB,dirFile);
                new File(dir+"//"+list.get(i).getCertificatesB()).renameTo(new File(dir+FileFinalValue.SPLITSYMBOL+list.get(i).getCertificatesId()+"B.jpg"));
            }*/
            File zip = new File(FileFinalValue.PICTUREPATH+FileFinalValue.SPLITSYMBOL+dirName+".zip");
            ZipUtils.doCompress(dirFile,zip);
            data = FileUtils.readFileToByteArray(zip);
            zip.delete();
            FileUtils.cleanDirectory(dirFile);
            dirFile.delete();
        }
        else{
            throw new ServiceExcep(ExcepEnum.PARERROR.getName(),ExcepEnum.PARERROR.getIndex());
        }
        return data;
    }


    private String[][] objToArray(List<Student> list){
        String[][] array = new String[list.size()][8];
        for (int j = 0,jLen = list.size();j<jLen;j++){
            array[j][0] = list.get(j).getUserName();
            array[j][1] = list.get(j).getSex() == 1?"男":"女";
            array[j][2] = list.get(j).getCertificatesId();
            array[j][3] = list.get(j).getTelnum();
            array[j][4] = list.get(j).getBespeak() == 2?"是":"否";
            array[j][5] = list.get(j).getLocationName();
            array[j][6] = list.get(j).getCreateDate();
            array[j][7] = list.get(j).getRecommend();
        }
        return array;
    }

}
